//
//  TitleCatalogCell.m
//  MoneyIndividual
//
//  Created by Le Anh Tai on 1/9/14.
//  Copyright (c) 2014 Le Anh Tai. All rights reserved.
//

#import "TitleCatalogCell.h"

@implementation TitleCatalogCell

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        self.textFieldMode = TextFieldInputModeTableView;
        _catalogView = [[TableView alloc] init];
        _catalogView.delegate = self;
        
        self.textField.clearButtonMode = UITextFieldViewModeNever;
        [self.toolbar addRightButtonWithTitle:NSLocalizedString(@"THÊM", nil)];
    }
    
    return self;
}

- (void)setCatalogs:(NSArray *)catalogs
{
    _catalogs = catalogs;
    
    _catalogView.objects = _catalogs;
}

- (void)setSelectedValue:(id)selectedValue
{
    [super setSelectedValue:selectedValue];
    
    self.textField.text = [selectedValue valueForKey:NAME_KEY];
}

#pragma mark - TextField delegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [super textFieldDidBeginEditing:textField];
    
    _catalogView.selectedObject = self.selectedValue;
    
    if (self.textFieldMode == TextFieldInputModeKeyboard)
    {
        [self.textField setInputView:nil];
        [self.toolbar removeRightButton];
    }
    else if (self.textFieldMode == TextFieldInputModeTableView)
    {
        [self.textField setInputView:_catalogView];
        [self.toolbar addRightButtonWithTitle:NSLocalizedString(@"THÊM", nil)];
    }
}

#pragma mark - ExpenseIncomeTypeView delegate
- (void)table:(TableView *)view didSelectManageObject:(id )selectedObject
{
    self.selectedValue = selectedObject;
    [self.textField resignFirstResponder];
}

- (void)inputToolbarDidPressRightButton:(InputToolbar *)toolbar
{
    self.textFieldMode = TextFieldInputModeKeyboard;
    [self.textField resignFirstResponder];
    [self.textField becomeFirstResponderAfterDelay];
}

- (void)inputToolbarDidPressCloseButton:(InputToolbar *)toolbar
{
    [super inputToolbarDidPressCloseButton:toolbar];
    
    self.textFieldMode = TextFieldInputModeTableView;
}
@end
